(function ($) {
    "use strict";

    function moveAllToRight(jq) {
        var all = undefined;
        jq.lbox.find("option").each(function () {
            if ($(this).css("display") != "none") {
                all = all ? all.add($(this)) : $(this);
            }
        });
        if(all){
            jq.rbox.find("select").append(all);
        }
        onOperate(jq);
    }

    function moveToRight(jq) {
        var all = undefined;
        jq.lbox.find("option:selected").each(function () {
            if ($(this).css("display") != "none") {
                all = all ? all.add($(this)) : $(this);
            }
        });
        if(all){
            jq.rbox.find("select").append(all);
        }
        onOperate(jq);
    }

    function moveToOther(jq, op) {
        var dv = op.closest("div");
        if(dv.is(jq.lbox)){
            jq.rbox.find("select").append(op);
        }else{
            jq.lbox.find("select").append(op);
        }
        onOperate(jq);
    }

    function moveAllToLeft(jq) {
        jq.rbox.find("option").appendTo(jq.lbox.find("select"));
        onOperate(jq);
    }

    function moveToLeft(jq) {
        jq.rbox.find("option:selected").appendTo(jq.lbox.find("select"));
        onOperate(jq);
    }

    function onOperate(wg) {
        var jq = wg.jq;
        var results = [];
        wg.rbox.find("option").each(function () {
            results.push($(this).val());
        });
        results = results.join(",");
        jq.val(results);
        wg.options.value = results;
    }

    function loader(jq, data) {
        return data.map(function (item) {
            return {id: item[jq.options.idFiled], text: item[jq.options.textFiled]};
        })
    }

    function _toHtml(records) {
        return records.map(function (item) {
            return "<option value='" + item.id + "'>" + item.text + "</option>";
        })
    }

    function reload(jq, lv, rv) {
        var url = jq.options.url, params = jq.options.params;
        $.ajax({
            type: 'POST',
            dataType: "json",
            url: url,
            data: params,
            success: function (data) {
                var result = jq.options.loader ? jq.options.loader(jq, data) : loader(jq, data), value = jq.options.value || "";
                var leftV = [], rightV = [];
                value = value.split(",");
                for (var i = 0, l = result.length; i < l; i++) {
                    var find = false;
                    for (var j = 0, k = value.length; j < k; j++) {
                        if (value[j] == result[i].id) {
                            find = true;
                            break;
                        }
                    }
                    find ? rightV.push(result[i]) : leftV.push(result[i]);
                }
                lv.html(_toHtml(leftV));
                rv.html(_toHtml(rightV));
                jq.container.find("option").on("dblclick", function(){
                    moveToOther(jq, $(this));
                });
            }
        });
    }

    function Component(ins, opt) {
        this.options = opt;
        var uuid = $.utils.createUUID(6);
        this.jq = $(ins);
        this.jq.wrap("<div id='" + uuid + "' class='hydra-inputtext-wrap'></div>");
        this.options.value = this.jq.val();
        this.container = $("#" + uuid);
        this.header = $("<div class='hydra-inputtext'></div>");
        this.lbox = $("<div class='hydra-listbox-select1 hydra-float'></div>");
        this.toolbar = $("<div class='hydra-btnbox1 hydra-float'></div>");
        this.rbox = $("<div class='hydra-listbox-select1 hydra-float'></div>");
        this.container.append(this.header).append(this.lbox).append(this.toolbar).append(this.rbox);
        var that = this;
        var lv = $("<select class='hydra-select1 for_ie6_hide' multiple></select>").appendTo(this.lbox);
        var rv = $("<select class='hydra-select1 for_ie6_hide' multiple></select>").appendTo(this.rbox);
        $('<input style="color:#788d95" placeholder="搜索" class="easyui-validatebox hydra-input-width validatebox-text" autocomplete="off">')
            .appendTo(this.header).on("input propertychange", function (event) {
                var v = $(this).val();
                if (!v.length) {
                    that.lbox.find("option").show();
                } else {
                    that.lbox.find("option").each(function () {
                        var h = $(this).html();
                        var reg = new RegExp(v,'g');
                        var reg_result = reg.test(h);
                        if(reg_result){
                            $(this).show();
                        }else{
                            $(this).hide();
                        }
                    });
                }
            });
        reload(this, lv, rv);
        this.toolbar.html("<a data-id='addAll' href='javascript:void(0)' iconCls='fa fa-angle-double-right fa-lg' plain='true'>添加所有</a><a href='javascript:void(0)' data-id='add' iconCls='fa fa-angle-right fa-lg' plain='true'>添加</a>" +
            "<a href='javascript:void(0)' data-id='del' iconCls='fa fa-angle-left fa-lg' plain='true'>删除</a><a href='javascript:void(0)' data-id='delAll' iconCls='fa fa-angle-double-left fa-lg' plain='true'>删除所有</a>").children()
            .linkbutton({
                onClick: function () {
                    var action = $(this).attr("data-id");
                    switch (action) {
                        case "addAll":
                            moveAllToRight(that);
                            break;
                        case "add":
                            moveToRight(that);
                            break;
                        case "del":
                            moveToLeft(that);
                            break;
                        case "delAll":
                            moveAllToLeft(that);
                            break;
                        default:
                            break;
                    }
                }
            });
    }

    $.fn.mutiSelect = function (opt) {
        $(this).each(function () {
            if (!$(this).data("mutiSelect")) {
                $(this).data("mutiSelect", new Component($(this), $.extend({}, $.fn.mutiSelect.defaults, opt)));
            }
        })
    };


    $.fn.mutiSelect.defaults = {};
})(jQuery);

